<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicModal
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'device:management:inDeviceManagement:edit'"
    @register="registerModalUpdate"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span>批量设备维护 </span>
    </template>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup >
  import { ref, unref, computed,defineEmits,watch,defineProps} from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { InDeviceManagement, inDeviceManagementSave, inDeviceManagementForm,inDeviceManagementListData,updateDevice } from '/@/api/device.management/inDeviceManagement';
  import {Office, officeTreeData,officeListData,officeTreeDataList} from '/@/api/sys/office';
  import {unitRegionListData} from '/@/api/unitmanage/unitRegion';
  import {unitBuildingListData} from '/@/api/unitmanage/unitBuilding';
  import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { inEquipmentTypeListData } from '/@/api/device.management/inEquipmentType';
  import { Image } from 'ant-design-vue';
  import { inFireHostListData } from '/@/api/device.management/inFireHost';




  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('device.management.inDeviceManagement');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<InDeviceManagement>({} as InDeviceManagement);
  const imageFire=ref()

      const props = defineProps({
      deviceList: {
        type: Array,
      }
    });
  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增') : t('编辑'),
  }));

  const ResEnterpriseId=ref<any>()


  const EnterpriseParams = ref<Recordable>({
     name:''
    });


  
const buildingName=ref('')

// 使用 computed 动态计算 params 对象
const selectParams = computed(() => {
  return {
    name: buildingName.value,
    unitCode:EnterpriseId.value? EnterpriseId.value : ResEnterpriseId.value,
  };
});


const RegionName=ref('')
const EnterpriseId=ref<any>()

const RegionParams = computed(() => {
  console.log('RegionName', EnterpriseId.value)
  return {
    name: RegionName.value,
    enterpriseId:EnterpriseId.value? ResEnterpriseId.value:ResEnterpriseId.value,
  };
});

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('企业名称'),
      field: 'enterpriseId',
      fieldLabel:'enterpriseName',
      component: 'Select',
      componentProps: () => {
        return {
          placeholder: t('请输入主体名称'),
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          allowClear: true,
          filterTreeNode: false,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
          onChange: (unitCode)=>{
            EnterpriseId.value=unitCode
            console.log('选择的企业:',unitCode)
          }
        };
      },
    },
    {
      label: t('安装建筑名称'),
      field: 'buildingId',
      fieldLabel:'buildingName',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
        api: unitBuildingListData,
          params:selectParams,
          resultField:'list',
          fieldNames: { label: 'name', value: 'id' },    
          allowClear:true,
          immediate:false,
          each:false,
          showSelect:true,
          optionFilterProp: 'label',
          showSearch:true,
          onSearch: (value) => {
          buildingName.value = value;
          // console.log('输入的值:', value);
        },
      },
      // required: true,
    },
    {
      label: t('区域名称'),
      field: 'regionId',
      fieldLabel:'regionName',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        api:unitRegionListData,
        params:RegionParams,
        resultField:'list',
          fieldNames: { label: 'name', value: 'id' },    
          allowClear:true,
          immediate:false,
          each:false,
          showSelect:true,
          optionFilterProp: 'label',
          showSearch:true,
          onSearch: (value) => {
          RegionName.value = value;
          console.log('输入的值:', RegionName.value);
        },
      },
      // required: true,
    },
    {
      label: t('维保周期'),
      field: 'maintenanceCycle',
      component: 'Select',
      componentProps: {
        options:[
          {
            label:'年度维保任务',
            value:'年度维保任务'
          }
        ]
      },
    },
    {
      label: t('设备类型'),
      field: 'deviceTypeCode',
      fieldLabel:'deviceType',
      component: 'Select',
      componentProps: {
        api:inEquipmentTypeListData,
        resultField:"list", 
        fieldNames:{
          label:'equipmentName',
          value:'equipmentCode'
        }
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerModalUpdate, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true });
    await resetFields();
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setModalProps({ loading: false });
  });
  

  async function handleSubmit() {
    try {
      let data = await validate();
      data={
        ...data,
        status:0,
        deviceList:props.deviceList,
      }
      console.log('data',data)
      setModalProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
      };
      // console.log('submit', params, data, record);
      const res = await updateDevice(params, data);
      showMessage(res.message);
      setTimeout(closeModal);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
